package com.thread;

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

public class ThreadIncurementLong3Method014 {

    static Long count = 0L;
    static AtomicLong count2 = new AtomicLong(0);
    static LongAdder count3 = new LongAdder();

    public static void main(String[] args) {
        Thread[] ts = new Thread[1000];
        for(int i=0;i<ts.length;i++){
            ts[i] = new Thread(()->{
                for(int k=0;k<100000;k++){
                    count2.incrementAndGet();
                }
            });
        }

        long start = System.currentTimeMillis();
        Arrays.stream(ts).forEach((thread -> {
            thread.start();
        }));

        Arrays.stream(ts).forEach((thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }));

        System.out.println("count2 = > " + count2 + "," + (System.currentTimeMillis()-start));

        System.out.println("-----------------------------------------");

        final Object lock = new Object();
        for(int i=0;i<ts.length;i++){
            ts[i] = new Thread(()->{
                for(int k=0;k<100000;k++){
                    synchronized (lock){
                        ++count;
                    }
                }
            });
        }
        start = System.currentTimeMillis();
        Arrays.stream(ts).forEach((thread -> {
            thread.start();
        }));

        Arrays.stream(ts).forEach((thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }));

        System.out.println("count = > "+count +"," + (System.currentTimeMillis()-start));
        System.out.println("-----------------------------------------");

        for(int i=0;i<ts.length;++i){
            ts[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    for(int k=0;k<100000;k++){
                        count3.add(1);
                    }
                }
            });
        }

        start = System.currentTimeMillis();
        Arrays.stream(ts).forEach((thread -> {
            thread.start();
        }));

        Arrays.stream(ts).forEach((thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }));

        System.out.println("count3 = > "+count3 +"," + (System.currentTimeMillis()-start));

    }
}
